<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户姓名" prop="uid">
        <el-select v-model="queryParams.uid" placeholder="请选择用户" style="width: 200px;">
          <el-option v-for="user in usersList" :key="user.id" :label="user.userName" :value="user.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="救援类型" prop="typeId">
        <el-select v-model="queryParams.typeId" placeholder="请选择救援类型" style="width: 200px;">
          <el-option v-for="dict in rescueTypeList" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="位置" prop="position">
        <el-input v-model="queryParams.position" placeholder="请输入位置" clearable @keyup.enter="handleQuery"
          style="width: 200px;" />
      </el-form-item>
      <el-form-item label="求助人院" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入求助人" clearable @keyup.enter="handleQuery"
          style="width: 200px;" />
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable @keyup.enter="handleQuery"
          style="width: 200px;" />
      </el-form-item>
      <el-form-item label="车牌编号" prop="carNum">
        <el-input
          v-model="queryParams.carNum"
          placeholder="请输入车牌编号"
          clearable
          @keyup.enter="handleQuery"
          style="width: 200px;"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['chy:rescue:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['chy:rescue:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['chy:rescue:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['chy:rescue:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="rescueList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="用户姓名" align="center" prop="uid">
        <template #default="scope">
          {{ getUserNameById(scope.row.uid) }}
        </template>
      </el-table-column>
      <el-table-column label="救援类型" align="center" prop="typeId">
        <template #default="scope">
          {{ getRescueType(scope.row.typeId) }}
        </template>
      </el-table-column>
      <el-table-column label="位置" align="center" prop="position" />
      <el-table-column label="求助人员" align="center" prop="name" />
      <el-table-column label="手机号码" align="center" prop="phone">
        <template #default="scope">
          {{ getUserPhoneById(scope.row.uid) }}
        </template>
      </el-table-column>
      <el-table-column label="车牌编号" align="center" prop="carNum" width="110">
        <template #default="scope">
          <el-tag type="primary">{{ scope.row.carNum }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="详情描述" align="center" prop="description" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="130">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['chy:rescue:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['chy:rescue:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改救援任务对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="rescueRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户姓名" prop="uid">
        <el-select v-model="form.uid" placeholder="请选择用户" @change="fillPhoneAndCarNums">
          <el-option v-for="user in usersList" :key="user.id" :label="user.userName" :value="user.id" />
        </el-select>
      </el-form-item>
        <el-form-item label="救援类型" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择救援类型">
            <el-option v-for="dict in rescueTypeList" :key="dict.id" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="位置" prop="position">
          <el-input v-model="form.position" placeholder="请输入位置" />
        </el-form-item>
        <el-form-item label="求助人员" prop="name">
          <el-input v-model="form.name" placeholder="请输入求助人" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <!-- 设置输入框为只读，禁止手动输入 -->
          <el-input v-model="form.phone" placeholder="请输入手机号" disabled/>
        </el-form-item>
        <el-form-item label="车牌编号" prop="carNum">
        <el-select
          v-model="form.carNum"
          placeholder="请选择车牌号"
          :disabled="!form.uid"
          @change="fillCarType"
        >
          <el-option v-for="carNum in availableCarNums" :key="carNum" :label="carNum" :value="carNum" />
        </el-select>
        <el-tag v-if="form.carNum" closable @close="clearCarNum" style="margin-top: 5px;">
          {{ form.carNum }}
        </el-tag>
      </el-form-item>
        <el-form-item label="详情描述">
          <editor v-model="form.description" :min-height="192" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Rescue">
import { ref } from "vue"
import { listRescue, getRescue, delRescue, addRescue, updateRescue } from "@/api/chy/rescue"
import { listRescue_type } from "@/api/chy/rescue_type"
import { listUsers } from "@/api/gas/users"
import { listUsercarinfo } from "@/api/chy/usercarinfo"

const { proxy } = getCurrentInstance()


const rescueTypeList = ref([])
const usercarinfoList = ref([])
const usersList = ref([])
const rescueList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const availableCarNums = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    uid: null,
    typeId: null,
    position: null,
    name: null,
    phone: null,
    carNum: null,
    description: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询救援任务列表 */
function getList() {
  loading.value = true
  listRescue(queryParams.value).then(response => {
    rescueList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
function getListUsers() {
  loading.value = true
  queryParams.value.params = {}
  listUsers(queryParams.value).then(response => {
    usersList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
function getRescueTypeList() {
  loading.value = true
  listRescue_type().then(response => {
    rescueTypeList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
/** 查询用户车辆列表 */
function getListUsersCars() {
  loading.value = true
  listUsercarinfo(queryParams.value).then(response => {
    usercarinfoList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
function getRescueType(typeId) {
  const rescueType = rescueTypeList.value.find(rescueType => rescueType.id == typeId)
  return rescueType ? rescueType.name : '未知类型'
}
/** 根据用户ID获取用户名 */
function getUserNameById(uid) {
  const user = usersList.value.find(user => user.id == uid)
  return user ? user.userName : '未知用户'
}
function getUserPhoneById(uid) {
  const user = usersList.value.find(user => user.id === uid)
  return user ? user.phone : '未知号码'
}

// 定义填充手机号码和筛选车牌编号的函数
function fillPhoneAndCarNums(uid) {
  const user = usersList.value.find(user => user.id === uid)
  if (user && user.phone) {
    form.value.phone = user.phone
  } else {
    form.value.phone = ''
  }
  // 清空车牌编号的选中内容
  form.value.carNum = null
  // 筛选出对应用户的车牌编号
  availableCarNums.value = usercarinfoList.value
    .filter(carInfo => carInfo.uid === uid)
    .map(carInfo => carInfo.carNum)
}

// 清除车牌编号选择
function clearCarNum() {
  form.value.carNum = null
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    uid: null,
    typeId: null,
    position: null,
    name: null,
    phone: null,
    carNum: null,
    description: null,
    deleted: null
  }
  proxy.resetForm("rescueRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加救援任务"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getRescue(_id).then(response => {
    form.value = response.data
    // 调用 fillPhoneAndCarNums 函数，根据用户 ID 筛选车牌编号
    fillPhoneAndCarNums(form.value.uid)
    open.value = true
    title.value = "修改救援任务"
  })
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["rescueRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRescue(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRescue(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除救援任务编号为"' + _ids + '"的数据项？').then(function () {
    return delRescue(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('chy/rescue/export', {
    ...queryParams.value
  }, `rescue_${new Date().getTime()}.xlsx`)
}

getList()
getRescueType()
getListUsers()
getRescueTypeList()
getListUsersCars()
</script>
